package com.horoscope.astrology.zodiac.signs.free.utils.dialog

import android.graphics.drawable.ColorDrawable
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.utils.SysUtils
import com.zyyoona7.wheel.WheelView

open class BaseDialogFragment : DialogFragment() {

    // 内存泄露问题处理
//    override fun onActivityCreated(savedInstanceState: Bundle?) {
//        super.onActivityCreated(savedInstanceState)
//        if (dialog != null) {
//            try { // 解决Dialog内D存泄漏
//                dialog.setOnShowListener(null)
//                dialog.setOnDismissListener(null)
//                dialog.setOnCancelListener(null)
//            } catch (e: Exception) {
//                e.printStackTrace()
//            }
//        }
//    }

    override fun onStart() {
        super.onStart()
        val win = dialog!!.window
        // 一定要设置Background，如果不设置，window属性设置无效
        win?.setBackgroundDrawable(
            ColorDrawable(
                ContextCompat.getColor(activity!!, R.color.transparent)
            )
        )
        dialog?.window?.attributes?.windowAnimations = R.style.dialog_style
        val dm = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getMetrics(dm)
        val params = win?.attributes
        params?.gravity = getGravity()
        params?.width = ViewGroup.LayoutParams.MATCH_PARENT
        params?.height = ViewGroup.LayoutParams.WRAP_CONTENT
        win?.attributes = params
    }

    // 统一WheelVew格式
    open fun setWheelView(wheelView: WheelView<String>, list: ArrayList<String>) {
        wheelView.data = list
        wheelView.normalItemTextColor = ContextCompat.getColor(activity!!, R.color.white_4)
        wheelView.selectedItemTextColor =
            ContextCompat.getColor(activity!!, R.color.horoscope_title_text)
        wheelView.dividerColor = ContextCompat.getColor(activity!!, R.color.color_CECE)
        wheelView.textSize = SysUtils.rp(20f).toFloat()
        wheelView.isShowDivider = true
        wheelView.lineSpacing = SysUtils.rp(20f).toFloat()
        wheelView.textBoundaryMargin = SysUtils.rp(5f).toFloat()
        wheelView.dividerHeight = SysUtils.rp(1f).toFloat()
        wheelView.selectedItemPosition = 1
    }

    //Dialog显示的位置
    open fun getGravity(): Int {
        return Gravity.BOTTOM
    }

    override fun show(manager: FragmentManager, tag: String?) {
        try {
            manager.beginTransaction().remove(this).commitAllowingStateLoss()
            super.show(manager, tag)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}